using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MediatR;
using User.Application.Contracts.Commands;
using User.Application.Contracts.Interfaces;
using User.Domain.Entities;
using User.Domain.ValueObjects;
using User.Domain.Repositories;

namespace User.Application.Commands
{
    public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, Guid>
    {
        private readonly IUserRepository _userRepository;
        private readonly IUnitOfWork _unitOfWork;
        public RegisterUserCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork)
        {
            _userRepository = userRepository;
            _unitOfWork = unitOfWork;
        }
        public async Task<Guid> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
        {
            
            var user = UserProfile.Register(
                request.id,
                request.nickName,
                request.phoneNumber != null ? PhoneNumber.From(request.phoneNumber) : null,
                request.address
            );

            await _userRepository.AddAsync(user);
            await _unitOfWork.SaveChangesAsync(cancellationToken);
            return await Task.FromResult(user.Id);
        }
    }
}